// package com.viprit.util.filesplit; - Not now

import java.io.*;

/**
 * Does the binary join of the specified files.
 *
 * @autho Vipul Modi
 *
 * <p>
 * <a href=mailto:vipul_modi@usa.net>Contact Author</a>
 */
public class JJoin
{
	/**
	 * Joins the specified files. The file names has the specified prefix and 
	 * specified number of pieces. Writes the joined pieces to the specified
	 * file name.
	 *
	 * @exception IOException error in reading the input files or writing in
	 * output file.
	 */
	public static void join(String inFilePrefix, int numPieces, String outFileName)
		throws IOException
	{
		// create the buffer
		byte[] buffer = new byte[1024];
		int numRead;

		// Read the input files and store it in output file.
		int piece = 1;
		boolean done = false;
		FileOutputStream fout = new FileOutputStream(outFileName);
		FileInputStream  fin  = new FileInputStream(inFilePrefix+piece);

		while(!done)
		{
			try
			{
				numRead = fin.read(buffer);
				if ( numRead > 0 )
				{
					fout.write(buffer, 0, numRead);
					fout.flush();
				}
				else
				{
					piece++;
					try{ fin.close(); } catch(IOException ioe1){}
					if ( piece > numPieces ) 
						done = true;
					else
						fin = new FileInputStream(inFilePrefix+piece);
				}
			}
			catch(EOFException e)
			{
				piece++;
				try{ fin.close(); } catch(IOException ioe1){}
				if ( piece > numPieces ) 
					done = true;
				else
					fin = new FileInputStream(inFilePrefix+piece);
			}
		}

		try
		{
			if ( fin != null )
				fin.close();
			fout.close();
		}
		catch(IOException ioe2)
		{
		}
	}

	public static void main(String[] args)
		throws IOException
	{
		if ( args.length < 3 ) 
		{
			System.out.println();
			System.out.println("usage :: java JJoin <inFilePrefix> <numSplits> <outfileName>");
			System.out.println();
			System.out.println("<inFilePrefix>\t : name of the splited files, wihout split count");
			System.out.println("<numSplits>\t : number of splits");
			System.out.println("<outfileName>\t : name of the outfile file, join of specified splits");
			System.out.println();
			return;
		}

		int numPieces = Integer.parseInt(args[1]);
		JJoin.join(args[0], numPieces, args[2]);
	}
}
